#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>

namespace ThreadModel
{
    template<class T>
    using func = std::function<void(T&)>;

    template<class T>
    class Thread
    {
    public:
        Thread(func<T> func, T& data, const std::string& name)
            :_func(func), _data(data), _threadName(name), _stop(true)
        {}
        ~Thread()
        {}
        void Excute()
        {
            _func(_data);
        }
        static void* threadrun(void* args) //非静态成员函数有默认的this指针
        {
            Thread<T>* self = static_cast<Thread<T>* >(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadrun, this);
            if(!n)
            {
                _stop = false;
                return true;
            }
            else
                return false;
        }
        void Join()
        {
            if(!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }
        void Detach()
        {
            if(!_stop)
            {
                pthread_detach(_tid);
            }
        }
        std::string name() const
        {
            return _threadName;
        }
        void Stop()
        {
            _stop = true;
        }
    private:

        pthread_t _tid;
        std::string _threadName;
        func<T> _func;
        T& _data;
        bool _stop; //线程是否停止
    };
}